package com.yanqu.road.server.manger.activity.tonbing;

import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.tonbing.config.TonBingCampBoxConfig;
import com.yanqu.road.entity.activity.tonbing.config.TonBingConfig;
import com.yanqu.road.entity.activity.tonbing.data.TonBingUserData;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.enums.activity.tonbing.eTonBingPosition;
import com.yanqu.road.entity.enums.activity.tonbing.eTonBingStage;
import com.yanqu.road.entity.player.UserHistoryAttribute;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.logic.activity.tonbing.logic.TonBingMapLogic;
import com.yanqu.road.logic.bussiness.activity.TonBingActivityBusiness;
import com.yanqu.road.logic.bussiness.player.UserHistoryAttributeBussiness;
import com.yanqu.road.logic.rank.UnionRankMsgModel;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.TonBingProto;
import com.yanqu.road.pb.union.cross.CrossUnionProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.tonbing.TonBingModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.PlayerModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.CommonActivityRankMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.pb.TonBingPb;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class TonBingMgr extends TempMgr {

    private static TonBingConfig config = null;

    private static RandomHelper randomHelper = new RandomHelper();

    private static final Set<Long> userIdSet = new HashSet<>(); // 赚速有变化的玩家ID

    /**
     * 重新加载活动
     */
    public static void reloadActivityData() {
        getLogger().info("reload TonBingActivity start");
        List<ActivityInfo> list = NormalActivityMgr.getOpenActivityInfoList(eActivityType.TonBingActivity.getValue());
        if (list.isEmpty()) {
            config = null;
            getLogger().info("reload TonBingActivity end, no activity in show time.");
            return;
        }
        ActivityInfo activityInfo = list.get(0);

        loadConfigFromDb(activityInfo);
        getLogger().info("reload TonBingActivity end, activityId {}.", config.getActivityInfo().getActivityId());

        for (GamePlayer player : GamePlayerMgr.getAllOnlinePlayer()) {
            player.getModule(TonBingModule.class).tonBingLogin();
        }
    }

    /**
     * 数据库加载配置
     */
    private static void loadConfigFromDb(ActivityInfo activityInfo) {
        Map<String, ActivityConfig> activityConfigMap = NormalActivityMgr.getActivityConfigMap(activityInfo.getActivityId());

        TonBingConfig tmpConfig = new TonBingConfig();
        tmpConfig.setActivityInfo(activityInfo);

        tmpConfig.setBuffTypeConfigMap(TonBingActivityBusiness.getTonBingBuffTypeConfigMap(activityInfo.getActivityId()));

        tmpConfig.setCityTypeConfigMap(TonBingActivityBusiness.getTonBingCityTypeConfigMap(activityInfo.getActivityId()));

        tmpConfig.setCityConfigMap(TonBingActivityBusiness.getTonBingCityConfigMap(activityInfo.getActivityId()));

        tmpConfig.setNpcEventConfigMap(TonBingActivityBusiness.getTonBingNpcEventConfigMap(activityInfo.getActivityId()));

        tmpConfig.setTitleConfigMap(TonBingActivityBusiness.getTonBingTitleConfigMap(activityInfo.getActivityId()));

        tmpConfig.setZiZhongItem(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_ITEM_CARGO.getName()).getIntValue());
        tmpConfig.setZhanGongItem(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_ITEM_SCORE.getName()).getIntValue());
        tmpConfig.setShenXingItem(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_ITEM_WALK_QUICKEN.getName()).getIntValue());
        tmpConfig.setZhanGuItem(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_ITEM_WAR_DRUM.getName()).getIntValue());
        tmpConfig.setBingFuItem(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_ITEM_SOLDIERS.getName()).getIntValue());

        String soldierRecruitParam = activityConfigMap.get(eActivityConfigType.PEAKTONGBING_SOLDIER_COST.getName()).getValue();
        Map<Long, Long> recruitSoldierMap = new ConcurrentHashMap<>();
        for (String tmpParam : StringUtils.stringToStringList(soldierRecruitParam, "\\|")) {
            List<Long> list = StringUtils.stringToLongList(tmpParam, ";");
            recruitSoldierMap.put(list.get(1), list.get(0));
        }
        tmpConfig.setRecruitSoldierMap(recruitSoldierMap);

        tmpConfig.setBattleCostTime(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_BATTLE_TIME.getName()).getIntValue() * DateHelper.SECOND_MILLIONS);

        tmpConfig.setCityEventConfigList(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_CITY_EVENT.getName()).getIntListValue(";"));

        tmpConfig.setCityEventInitConfigList(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_CITY_EVENT_INIT.getName()).getIntListValue("\\|"));

        List<String> cityEventTimeParam = StringUtils.stringToStringList(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_CITY_EVENT_TIME.getName()).getValue(), "\\|");
        List<Integer> cityEventTimeParam1 = StringUtils.stringToIntegerList(cityEventTimeParam.get(0), ";");
        List<Integer> cityEventTimeParam2 = StringUtils.stringToIntegerList(cityEventTimeParam.get(1), ";");
        tmpConfig.setCityEventRefreshTime(cityEventTimeParam1.stream().mapToLong(item -> item * DateHelper.HOUR_MILLIONS).boxed().collect(Collectors.toList()));
        tmpConfig.setCityEventApplyTime(cityEventTimeParam2.stream().mapToLong(item -> item * DateHelper.HOUR_MILLIONS).boxed().collect(Collectors.toList()));

        tmpConfig.setMoveTime(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_CITY_MOVE_TIME.getName()).getLongValue() * DateHelper.SECOND_MILLIONS);
        tmpConfig.setMoveTimeFast(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_OWN_CITY_MOVE_TIME.getName()).getLongValue() * DateHelper.SECOND_MILLIONS);

        tmpConfig.setWoundedSoldierMaxNum(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_WOUNDED_SOLDIER_NUM_LIMIT.getName()).getLongValue());

        tmpConfig.setWoundedSoldierPercent(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_WOUNDED_SOLDIER_CONVERT_RATE.getName()).getLongValue());

        List<Integer> woundedRescueParam = activityConfigMap.get(eActivityConfigType.PEAKTONGBING_WOUNDED_SOLDIER_RESCUE_SPEED.getName()).getIntListValue(";");
        tmpConfig.setWoundedRescueTime(woundedRescueParam.get(1) * DateHelper.SECOND_MILLIONS);
        tmpConfig.setWoundedRescueCount(woundedRescueParam.get(0));

        tmpConfig.setNpcEventMaxNum(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_NPC_EVENT_EXIST_NUM_LIMIT.getName()).getIntValue());
        tmpConfig.setNpcEventInterval(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_NPC_EVENT_REFRESH_INTERVAL.getName()).getIntValue() * DateHelper.HOUR_MILLIONS);
        tmpConfig.setNpcEventDayMaxNum(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_NPC_EVENT_NUM_LIMIT.getName()).getIntValue());
        tmpConfig.setNpcEventBeginTime(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_NPC_EVENT_REFRESH_TIME.getName()).getIntValue() * DateHelper.HOUR_MILLIONS);

        List<Integer> joinParam = activityConfigMap.get(eActivityConfigType.PEAKTONGBING_CAMP_RULE.getName()).getIntListValue(";");
        tmpConfig.setUnionNum(joinParam.get(0));
        tmpConfig.setCampNum(joinParam.get(1));

        List<Integer> createTimeParam = activityConfigMap.get(eActivityConfigType.PEAKTONGBING_CREATE_TEAM_TIME.getName()).getIntListValue(";");
        List<Long> joinTimeList = new ArrayList<>();
        joinTimeList.add(activityInfo.getBeginTime() * 1000L + (createTimeParam.get(0) - 1) * DateHelper.DAY_MILLIONS + createTimeParam.get(1) * DateHelper.HOUR_MILLIONS);
        joinTimeList.add(activityInfo.getBeginTime() * 1000L + (createTimeParam.get(0) - 1) * DateHelper.DAY_MILLIONS + createTimeParam.get(2) * DateHelper.HOUR_MILLIONS);
        tmpConfig.setJoinTimeList(joinTimeList);

        List<String> stage1TimeParam = activityConfigMap.get(eActivityConfigType.PEAKTONGBING_FIRST_STAGE_TIME.getName()).getStringListValue("\\|");
        List<List<Long>> stage1TimeList = new ArrayList<>();
        for (String tmp : stage1TimeParam) {
            List<Integer> tmpList = StringUtils.stringToIntegerList(tmp, ";");
            List<Long> stage1Time = new ArrayList<>();
            stage1Time.add(activityInfo.getBeginTime() * 1000L + (tmpList.get(0) - 1) * DateHelper.DAY_MILLIONS + tmpList.get(1) * DateHelper.HOUR_MILLIONS);
            stage1Time.add(activityInfo.getBeginTime() * 1000L + (tmpList.get(0) - 1) * DateHelper.DAY_MILLIONS + tmpList.get(2) * DateHelper.HOUR_MILLIONS);
            stage1TimeList.add(stage1Time);
            //开始时间，用来生成轮次数据
            stage1Time.add(activityInfo.getBeginTime() * 1000L + (tmpList.get(0) - 1) * DateHelper.DAY_MILLIONS);
            stage1Time.add(activityInfo.getBeginTime() * 1000L + (tmpList.get(0)) * DateHelper.DAY_MILLIONS);
            stage1TimeList.add(stage1Time);
        }
        tmpConfig.setStage1TimeList(stage1TimeList);
        tmpConfig.setWarTypeCount(stage1TimeParam.size());

        Map<Integer,Long> tempStage2BeginTimeMap = new ConcurrentHashMap<>();
        List<String> stage2ParamStrList = activityConfigMap.get(eActivityConfigType.PEAKTONGBING_SECOND_STAGE_TIME.getName()).getStringListValue("\\|");
        for(String stage2ParamStr : stage2ParamStrList){
            List<Integer> stage2Param = StringUtils.stringToIntegerList(stage2ParamStr,";");
            tempStage2BeginTimeMap.put(stage2Param.get(0),activityInfo.getBeginTime() * 1000L + (stage2Param.get(0) - 1) * DateHelper.DAY_MILLIONS + stage2Param.get(1) * DateHelper.HOUR_MILLIONS);
        }
        tmpConfig.setStage2BeginTimeMap(tempStage2BeginTimeMap);

        tmpConfig.setTeamAuxiliaryPatronsNum(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_PLAYER_TEAM_LIEUTENANT_NUM.getName()).getIntValue());

        Map<Integer, TonBingCampBoxConfig> campBoxConfigMap = new ConcurrentHashMap<>();
        for (String campBoxPara : StringUtils.stringToStringList(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_CAMP_GIFT_BAG.getName()).getValue(), "\\|")) {
            List<Integer> list = StringUtils.stringToIntegerList(campBoxPara, ";");
            TonBingCampBoxConfig campBoxConfig = new TonBingCampBoxConfig();
            campBoxConfig.setKey(list.get(0));
            campBoxConfig.setBoxId(list.get(1));
            campBoxConfig.setBoxScore(list.get(2));
            campBoxConfigMap.put(campBoxConfig.getKey(), campBoxConfig);
        }
        tmpConfig.setCampBoxConfigMap(campBoxConfigMap);

        List<Long> list = StringUtils.stringToLongList(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_TEAM_NUM_LIMIT_PARAM.getName()).getValue(), ";");
        tmpConfig.setTeamSoldierMaxNumParam(list);

        tmpConfig.setTeamNumLowerLimitParam(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_TEAM_NUM_LOWER_LIMIT_PARAM.getName()).getLongValue());
        tmpConfig.setTeamNumLowerLimitFixedParam(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_TEAM_NUM_LOWER_LIMIT_FIXED_PARAM.getName()).getLongValue());

        tmpConfig.setBattleParam(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_SOLDIER_LOST_PARAM.getName()).getIntListValue(";"));

        tmpConfig.setZhanGongParam(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_ITEM_SCORE_PARAM.getName()).getIntListValue(";"));

        tmpConfig.setContinueWinReportTimes(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_BARRAGE_STREAK_NUM.getName()).getIntValue());

        tmpConfig.setNeedHelpCd(DateHelper.HOUR_MILLIONS * activityConfigMap.get(eActivityConfigType.PEAKTONGBING_HELP_TIME.getName()).getIntValue());

        tmpConfig.setUserReportNum(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_PERSONAL_BATTLE_REPORT_NUM_LIMIT.getName()).getIntValue());
        tmpConfig.setCityReportNum(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_CAMP_BATTLE_REPORT_NUM_LIMIT.getName()).getIntValue());

        List<String> lightParam = StringUtils.stringToStringList(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_SPECIAL_SHOW.getName()).getValue(), "\\|");
        int lightNum = StringUtils.stringToIntegerList(lightParam.get(lightParam.size() - 1), ";").get(1);
        tmpConfig.setLightRankNum(lightNum);

        tmpConfig.setBarrackLimitParam(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_BARRACK_NUM_LIMIT_PARAM.getName()).getIntValue());

        String worshipRewardStr = activityConfigMap.get(eActivityConfigType.PEAKTONGBING_WORSHIP_REWARD_PARAM.getName()).getValue();
        Map<Integer, List<Integer>> worshipRewardMap = new ConcurrentHashMap<>();
        for (String tmpParam : StringUtils.stringToStringList(worshipRewardStr, "\\|")) {
            List<String> strList = StringUtils.stringToStringList(tmpParam, "=");
            List<Integer> intList = StringUtils.stringToIntegerList(strList.get(1), ";");
            worshipRewardMap.put(Integer.valueOf(strList.get(0)), intList);
        }
        tmpConfig.setWorshipRewardMap(worshipRewardMap);

        tmpConfig.setWinDecorationId(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_FIRST_TITLE_ID.getName()).getIntValue());

        List<Integer> showParam = activityConfigMap.get(eActivityConfigType.PEAKTONGBING_SCREEN_SHOW_RULE.getName()).getIntListValue("\\|");
        tmpConfig.setShowCampInScreenNum(showParam.get(0));
        tmpConfig.setShowCampOutScreenNum(showParam.get(1));

        tmpConfig.setShowCampTopNum(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_TEAM_SHOW_RULE.getName()).getIntValue());

        tmpConfig.setMailFirstTitleReward(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_MAIL_FIRST_TITLE_REWORD.getName()).getValue());
        tmpConfig.setMailFirstContentReward(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_MAIL_CONTENT_FIRST_REWORD.getName()).getValue());
        tmpConfig.setMailWinTitleReward(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_MAIL_WIN_TITLE_REWORD.getName()).getValue());
        tmpConfig.setMailWinContentReward(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_MAIL_CONTENT_WIN_REWORD.getName()).getValue());

        tmpConfig.setBattlefieldPartParam(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_BATTLE_PLACE_PARAM.getName()).getIntValue());

        tmpConfig.setBattlePrepareTime(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_BATTLE_READY_TIME.getName()).getLongValue() * DateHelper.SECOND_MILLIONS);

        tmpConfig.setSyncPatronsCd(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_POWER_COOL_DOWN_TIME.getName()).getLongValue() * DateHelper.HOUR_MILLIONS);

        tmpConfig.setCityDefTeamNameKey(eActivityConfigType.PEAKTONGBING_CITY_SOLDIER_NAME.getName()); // 相当于写死

        tmpConfig.setCityTeamRecoveryTime(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_CITY_SOLDIER_RECOVER_TIME.getName()).getLongValue() * DateHelper.SECOND_MILLIONS);

        tmpConfig.setLightNeedZhanGong(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_LIGHT_NEED_ZHANGONG.getName()).getLongValue());

        tmpConfig.setRedDotCollectCount(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_RED_DOT_COLLECT_COUNT.getName()).getLongValue());

        tmpConfig.setRedDotCureNum(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_RED_DOT_CURE_NUM.getName()).getLongValue());

        tmpConfig.setZiZhongTitle(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_MAIL_TITLE_FOOD_REWORD.getName()).getValue());
        tmpConfig.setZiZhongContent(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_MAIL_CONTENT_FOOD_REWORD.getName()).getValue());
        tmpConfig.setAppointScoreLimit(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_APPOINT_ITEM_SCORE_LIMIT.getName()).getLongValue());

        tmpConfig.setSkinsExchangeParam(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_SKINS_EXCHANGE_PARAM.getName()).getValue());

        if (!activityConfigMap.containsKey(eActivityConfigType.PEAKTONGBING_GUILD_GROUP_RULE.getName())) { // 兼容统兵的旧规则
            tmpConfig.setGuildGroupRule("");
        } else {
            tmpConfig.setGuildGroupRule(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_GUILD_GROUP_RULE.getName()).getValue()); // 商会分组转换规则
        }

        if (!activityConfigMap.containsKey(eActivityConfigType.PEAKTONGBING_GROUP_PARAM.getName())) { // 兼容
            tmpConfig.setGroup("");
        } else {
            tmpConfig.setGroup(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_GROUP_PARAM.getName()).getValue()); // 商会特殊分组范围
        }

        // 这两个不读库
        tmpConfig.setNpcEventPositionNum(TonBingMapLogic.getNpcEventPosNumConfig());
        tmpConfig.setCityConnectMap(TonBingMapLogic.getCityConnectMapConfig());


        //统兵演武新加的
        tmpConfig.setGroupRuleList(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_GROUP_RULE.getName()).getValue());
        tmpConfig.setGroupRuleList(activityConfigMap.get(eActivityConfigType.PEAKTONGBING_GROUP_CHAMBER_NUM_MAX.getName()).getValue());

        String worshipRewardStr2 = activityConfigMap.get(eActivityConfigType.PEAKTONGBING_EMPEROR_WORSHIP_REWARD_PARAM.getName()).getValue();
        Map<Integer, List<Integer>> worshipReward2Map = new ConcurrentHashMap<>();
        for (String tmpParam : StringUtils.stringToStringList(worshipRewardStr2, "\\|")) {
            List<String> strList = StringUtils.stringToStringList(tmpParam, "=");
            List<Integer> intList = StringUtils.stringToIntegerList(strList.get(1), ";");
            worshipReward2Map.put(Integer.valueOf(strList.get(0)), intList);
        }
        tmpConfig.setWorshipRewardMap2(worshipReward2Map);
        String worshipRewardStr3 = activityConfigMap.get(eActivityConfigType.PEAKTONGBING_EMPEROR_WORSHIP_REWARD_RANK.getName()).getValue();
        Map<Integer, List<Integer>> worshipReward3Map = new ConcurrentHashMap<>();
        for (String tmpParam : StringUtils.stringToStringList(worshipRewardStr3, "\\|")) {
            List<String> strList = StringUtils.stringToStringList(tmpParam, "=");
            List<Integer> intList = StringUtils.stringToIntegerList(strList.get(1), ";");
            worshipReward3Map.put(Integer.valueOf(strList.get(0)), intList);
        }
        tmpConfig.setWorshipRewardMap3(worshipReward3Map);
        config = tmpConfig;
    }

    /**
     * 拿配置
     */
    public static TonBingConfig getConfig() {
        return config;
    }

    /**
     * 拿活动信息
     */
    public static ActivityInfo getActivityInfo() {
        return config == null ? null : config.getActivityInfo();
    }

    /**
     * 上传商会赚速变化
     */
    public static void uploadUnionEarnSpeedChange() {
        if (userIdSet.isEmpty()) {
            return;
        }

        if (config == null || config.getTonBingStage() != eTonBingStage.JoinTime) {
            return;
        }

        ArrayList<Long> userIdList;
        synchronized (userIdSet) {
            userIdList = new ArrayList<>(userIdSet);
            userIdSet.clear();
        }

        TonBingProto.CrossTonBingGetMemberRespMsg.Builder builder = TonBingProto.CrossTonBingGetMemberRespMsg.newBuilder();
        builder.setActivityId(config.getActivityInfo().getActivityId());
        for (long userId : userIdList) {
            UserInfo userInfo = UserMgr.getUserInfo(userId);
            if (userInfo != null) {
                TonBingProto.TonBingUnionMemberMsg.Builder tmp = TonBingProto.TonBingUnionMemberMsg.newBuilder();
                tmp.setUserId(userInfo.getUserId());
                tmp.setUnionUid(userInfo.getUnionUid());
                tmp.setEarnSpeed(userInfo.getEarnSpeed().toString());
                tmp.setPatronsTopAbility(getTopPatronsAbility(userId));
                builder.addMember(tmp);
            }
        }

        GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(CrossProtocol.C2_CROSS_TON_BING_GET_UNION_MEMBER_RESP, builder));
    }

    /**
     * 通知跨服商会成员变了
     */
    public static void unionChange(String unionUid) {
        try {
            //商会成员变更职位变了
            TonBingConfig config = TonBingMgr.getConfig();
            if (config != null && ActivityMgr.activityInTime(config.getActivityInfo())) {
                TonBingProto.CrossTonBingNotifyUnionMemberChangeReqMsg.Builder builder = TonBingProto.CrossTonBingNotifyUnionMemberChangeReqMsg.newBuilder();
                builder.setActivityId(config.getActivityInfo().getActivityId());
                builder.setUnionUid(unionUid);
                YanQuMessage message = YanQuMessageUtils.buildMessage(CrossProtocol.C2_CROSS_TON_BING_NOTIFY_UNION_MEMBER_CHANGE_REQ, builder);
                GamePlayerMgr.sendPacket(0, message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查有没有缓存到报名期排行
     */
    public static void checkRegistrationList() {
        if (config == null || config.getActivityInfo() == null) {
            return;
        }
        ActivityInfo activityInfo = config.getActivityInfo();
        UnionRankMsgModel model = CommonActivityRankMgr.getUnionRankMsgModel(activityInfo.getActivityId());
        if (null != model) {
            model.setRankNum(config.getUnionNum() + 50);
            model.setActivityEndTime(activityInfo.getEndShowTime());
            if (model.getRankListMsg().getRankListCount() == 0 && !model.isInReq()) {
                CrossUnionProto.CrossUnionGetMaxAbilityUnionRankListReq.Builder crossReqMsg = CrossUnionProto.CrossUnionGetMaxAbilityUnionRankListReq.newBuilder();
                crossReqMsg.setActivityId(activityInfo.getActivityId());
                crossReqMsg.addAllServerIds(activityInfo.getServerIdList());
                crossReqMsg.setRankNum(model.getRankNum());
                crossReqMsg.setActivityEndTime(activityInfo.getEndShowTime());
                GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(Protocol.C_UNION_GET_MAX_ABILITY_UNION_RANK_LIST, crossReqMsg));
            }
        }
    }

    /**
     * 获取门客最高赚钱
     */
    private static String getTopPatronsAbility(long userId) {
        GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(userId);
        if (onlinePlayer != null) {
            return onlinePlayer.getModule(PlayerModule.class).getUserHistoryAttribute().getAbility().toString();
        } else {
            UserHistoryAttribute userHistoryAttribute = UserHistoryAttributeBussiness.getUserHistoryAttribute(userId);
            if (userHistoryAttribute == null) {
                return "0";
            }
            return userHistoryAttribute.getAbility().toString();
        }
    }

    /**
     * 是否为城主
     */
    public static boolean isTonBingMaster(long userId) {
        // 活动不存在或者不在活动期间内
        if (config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return false;
        }
        GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(userId);
        if (onlinePlayer != null) {
            return onlinePlayer.getModule(TonBingModule.class).isTonBingMaster();
        } else {
            TonBingUserData userData = TonBingActivityBusiness.getTonBingUserData(config.getActivityInfo().getActivityId(), userId);
            if (userData == null) {
                return false;
            }
            Map<Integer,Integer> posMap = userData.getPositionMap();
            if(posMap.containsKey(0)){
                return posMap.get(0) == eTonBingPosition.Master.getValue();
            }
            return false;
        }
    }

    /**
     * 记录赚速有变化的商会
     */
    public static void addUnionEarnSpeedChange(long userId) {
        synchronized (userIdSet) {
            userIdSet.add(userId);
        }
    }

    /**
     * 获取膜拜奖励
     */
    public static String getWorshipReward(){
        Property rewardProperty = new Property();
        Map<Integer, List<Integer>> worshipRewardMap = config.getWorshipRewardMap();
        for(int goodsId : worshipRewardMap.keySet()){
            List<Integer> randomValueList = worshipRewardMap.get(goodsId);
            rewardProperty.addProperty(goodsId, BigInteger.valueOf(randomHelper.next(randomValueList.get(0),randomValueList.get(1) + 1)));
        }
        return PropertyHelper.parsePropertyToString(rewardProperty);
    }
    public static String getWorshipReward2(){
        Property rewardProperty = new Property();
        Map<Integer, List<Integer>> worshipRewardMap = config.getWorshipRewardMap2();
        for(int goodsId : worshipRewardMap.keySet()){
            List<Integer> randomValueList = worshipRewardMap.get(goodsId);
            rewardProperty.addProperty(goodsId, BigInteger.valueOf(randomHelper.next(randomValueList.get(0),randomValueList.get(1) + 1)));
        }
        return PropertyHelper.parsePropertyToString(rewardProperty);
    }
    public static String getWorshipReward3(){
        Property rewardProperty = new Property();
        Map<Integer, List<Integer>> worshipRewardMap = config.getWorshipRewardMap3();
        for(int goodsId : worshipRewardMap.keySet()){
            List<Integer> randomValueList = worshipRewardMap.get(goodsId);
            rewardProperty.addProperty(goodsId, BigInteger.valueOf(randomHelper.next(randomValueList.get(0),randomValueList.get(1) + 1)));
        }
        return PropertyHelper.parsePropertyToString(rewardProperty);
    }

    /**
     * 商会能否变化人员
     */
    public static boolean canChangeUnion() {
        long now = System.currentTimeMillis();
        if (config != null
                && now > config.getJoinTimeList().get(1) // [报名期结束,活动结束] 无法退出
                && now < config.getActivityInfo().getEndTime() * 1000L) {
            return false;
        }
        return true;
    }

    /**
     * 是否是马
     */
    public static boolean isHorseItem(int goodsId) {
        GoodsInfo goodsInfo = GoodsMgr.getGoodsById(goodsId);
        if (goodsInfo != null) {
            if (goodsInfo.getType() == eGoodsType.TonBingHorse.getValue() && goodsInfo.getParamList().get(1).intValue() == 0) {
                return true;
            }
        }
        return false;
    }

    /**
     * 加马
     */
    public static void addHorse(GamePlayer player, int goodsId, long count, int logType) {
        getLogger().info("ton bing add horse : userId {} goodsId {} count {} logType {}.", player.getUserId(), goodsId, count, logType);

        if (config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            getLogger().error("ton bing add horse fail! no activity! userId {}.", player.getUserId());
            return;
        }

        GoodsInfo goodsInfo = GoodsMgr.getGoodsById(goodsId);
        if (goodsInfo == null) {
            getLogger().error("ton bing add horse fail! no goodsInfo! userId {}.", player.getUserId());
            return;
        }
        int horseId = goodsInfo.getParamList().get(0).intValue();

        TonBingProto.CrossTonBingChangeHorseReqMsg.Builder builder = TonBingProto.CrossTonBingChangeHorseReqMsg.newBuilder();
        builder.setActivityId(config.getActivityInfo().getActivityId());
        builder.setHorse(horseId);
        player.sendPacket(CrossProtocol.C2_TON_BING_UPDATE_HORSE, builder);
    }

    /**
     * 同步演武统兵门客数据
     * @param isRefreshMaxSoldier 是否只刷新兵力上限
     */
    public static void syncTonBingPatronsAbility(GamePlayer player, boolean isRefreshMaxSoldier) {
        if (config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return;
        }
        if (!config.inEnterActivityTime()) {
            return;
        }
        TonBingProto.CrossTonBingUpdatePatronsReqMsg.Builder builder = TonBingProto.CrossTonBingUpdatePatronsReqMsg.newBuilder();
        builder.setActivityId(config.getActivityInfo().getActivityId());
        builder.setUserId(player.getUserId());
        builder.addAllPatrons(TonBingPb.parseTonBingPatronsListMsg(player.getModule(PatronsModule.class).getUserPatronsList()));
        builder.addAllSoldierAddition(player.getModule(PatronsModule.class).getTonBingSoldierAddition());
        builder.setIsRefreshMaxSoldier(isRefreshMaxSoldier);
        player.sendPacket(CrossProtocol.C2_CROSS_TON_BING_PATRONS_SYNC, builder);
    }

    public static boolean hasActivity() {
        if (getActivityInfo() == null || config == null) {
            return false;
        }
        return true;
    }

    public static boolean isInRegistration() {
        if(config != null && config.getActivityInfo() != null){
            if(ActivityMgr.activityInShowTime(config.getActivityInfo())){
                return config.getTurn() == 0;
            }
        }
        return false;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }
}
